package org.mat.ipaas.ucenter.service.modules.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.mat.framework.lang.dto.MatApiResponse;
import org.mat.ipaas.ucenter.biz.common.system.query.QueryGenerator;
import org.mat.ipaas.ucenter.biz.modules.system.entity.SysUserAgent;
import org.mat.ipaas.ucenter.biz.modules.system.service.ISysUserAgentService;
import org.mat.ipaas.ucenter.service.api.system.SysUserAgentRestAPI;
import org.mat.ipaas.ucenter.service.dto.system.entity.SysUserAgentDTO;
import org.mat.ipaas.ucenter.service.modules.SessionService;
import org.mat.ipaas.ucenter.service.util.SessionUtils;
import org.mat.ipaas.ucenter.service.dto.system.vo.LoginUserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @Title: Controller
 * 用户代理人设置
 */
@RestController
@RequestMapping("/sys/sysUserAgent")
@Slf4j
public class SysUserAgentController implements SysUserAgentRestAPI {

    @Autowired
    private SessionService sessionService;

    @Autowired
    private ISysUserAgentService sysUserAgentService;

    @Value("${mat.path.upload}")
    private String upLoadPath;

    /**
     * 分页列表查询
     *
     * @param sysUserAgentDTO
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping(value = "/list")
    public MatApiResponse<IPage<SysUserAgentDTO>> queryPageList(@SpringQueryMap SysUserAgentDTO sysUserAgentDTO,
                                                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        MatApiResponse<IPage<SysUserAgentDTO>> matApiResponse = new MatApiResponse<>();
        SysUserAgent sysUserAgent = toSysUserAgent(sysUserAgentDTO);

        QueryWrapper<SysUserAgent> queryWrapper = QueryGenerator.initQueryWrapper(sysUserAgent, request.getParameterMap());
        Page<SysUserAgent> page = new Page<SysUserAgent>(pageNo, pageSize);
        IPage<SysUserAgent> pageList = sysUserAgentService.page(page, queryWrapper);
        matApiResponse.setSuccess(true);
        matApiResponse.setData(toSysUserAgentDTOPage(pageList));
        return matApiResponse;
    }

    /**
     * 添加
     *
     * @param sysUserAgentDTO
     * @return
     */
    @PostMapping(value = "/add")
    public MatApiResponse<SysUserAgentDTO> add(@RequestBody SysUserAgentDTO sysUserAgentDTO) {
        MatApiResponse<SysUserAgentDTO> matApiResponse = new MatApiResponse<>();
        SysUserAgent sysUserAgent = toSysUserAgent(sysUserAgentDTO);

        try {
            sysUserAgentService.save(sysUserAgent);
            matApiResponse.success("代理人设置成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            matApiResponse.fail("操作失败");
        }
        return matApiResponse;
    }

    /**
     * 编辑
     *
     * @param sysUserAgentDTO
     * @return
     */
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public MatApiResponse<SysUserAgentDTO> edit(@RequestBody SysUserAgentDTO sysUserAgentDTO) {
        MatApiResponse<SysUserAgentDTO> matApiResponse = new MatApiResponse<>();
        SysUserAgent sysUserAgent = toSysUserAgent(sysUserAgentDTO);

        SysUserAgent sysUserAgentEntity = sysUserAgentService.getById(sysUserAgent.getId());
        if (sysUserAgentEntity == null) {
            matApiResponse.fail("未找到对应实体");
        } else {
            boolean ok = sysUserAgentService.updateById(sysUserAgent);
            //TODO 返回false说明什么？
            if (ok) {
                matApiResponse.success("代理人设置成功!");
            }
        }

        return matApiResponse;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/delete")
    public MatApiResponse<SysUserAgentDTO> delete(@RequestParam(name = "id", required = true) String id) {
        MatApiResponse<SysUserAgentDTO> matApiResponse = new MatApiResponse<>();
        SysUserAgent sysUserAgent = sysUserAgentService.getById(id);
        if (sysUserAgent == null) {
            matApiResponse.fail("未找到对应实体");
        } else {
            boolean ok = sysUserAgentService.removeById(id);
            if (ok) {
                matApiResponse.success("删除成功!");
            }
        }

        return matApiResponse;
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping(value = "/deleteBatch")
    public MatApiResponse<SysUserAgentDTO> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        MatApiResponse<SysUserAgentDTO> matApiResponse = new MatApiResponse<>();
        if (ids == null || "".equals(ids.trim())) {
            matApiResponse.fail("参数不识别！");
        } else {
            this.sysUserAgentService.removeByIds(Arrays.asList(ids.split(",")));
            matApiResponse.success("删除成功!");
        }
        return matApiResponse;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryById")
    public MatApiResponse<SysUserAgentDTO> queryById(@RequestParam(name = "id", required = true) String id) {
        MatApiResponse<SysUserAgentDTO> matApiResponse = new MatApiResponse<>();
        SysUserAgent sysUserAgent = sysUserAgentService.getById(id);
        if (sysUserAgent == null) {
            matApiResponse.fail("未找到对应实体");
        } else {
            matApiResponse.setData(toSysUserAgentDTO(sysUserAgent));
            matApiResponse.setSuccess(true);
        }
        return matApiResponse;
    }

    /**
     * 通过userName查询
     *
     * @param userName
     * @return
     */
    @GetMapping(value = "/queryByUserName")
    public MatApiResponse<SysUserAgentDTO> queryByUserName(@RequestParam(name = "userName", required = true) String userName) {
        MatApiResponse<SysUserAgentDTO> matApiResponse = new MatApiResponse<>();
        LambdaQueryWrapper<SysUserAgent> queryWrapper = new LambdaQueryWrapper<SysUserAgent>();
        queryWrapper.eq(SysUserAgent::getUserName, userName);
        SysUserAgent sysUserAgent = sysUserAgentService.getOne(queryWrapper);
        if (sysUserAgent == null) {
            matApiResponse.fail("未找到对应实体");
        } else {
            matApiResponse.setData(toSysUserAgentDTO(sysUserAgent));
            matApiResponse.setSuccess(true);
        }
        return matApiResponse;
    }

    /**
     * 导出excel
     *
     * @param sysUserAgentDTO
     * @param request
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(SysUserAgentDTO sysUserAgentDTO, HttpServletRequest request) {
        SysUserAgent sysUserAgent = toSysUserAgent(sysUserAgentDTO);

        // Step.1 组装查询条件
        QueryWrapper<SysUserAgent> queryWrapper = QueryGenerator.initQueryWrapper(sysUserAgent, request.getParameterMap());
        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<SysUserAgent> pageList = sysUserAgentService.list(queryWrapper);
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "用户代理人设置列表");
        mv.addObject(NormalExcelConstants.CLASS, SysUserAgent.class);
        LoginUserDTO user = sessionService.getLoginUser();

        ExportParams exportParams = new ExportParams("用户代理人设置列表数据", "导出人:" + user.getRealname(), "导出信息");
        exportParams.setImageBasePath(upLoadPath);
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public MatApiResponse<?> importExcel() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<SysUserAgent> listSysUserAgents = ExcelImportUtil.importExcel(file.getInputStream(), SysUserAgent.class, params);
                for (SysUserAgent sysUserAgentExcel : listSysUserAgents) {
                    sysUserAgentService.save(sysUserAgentExcel);
                }
                return MatApiResponse.success("文件导入成功！数据行数：" + listSysUserAgents.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return MatApiResponse.fail("文件导入失败！");
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return MatApiResponse.fail("文件导入失败！");
    }


    private Page<SysUserAgentDTO> toSysUserAgentDTOPage(IPage<SysUserAgent> pageList) {
        Page<SysUserAgentDTO> sysUserAgentDTOPage = new Page<>();
        List<SysUserAgentDTO> sysUserAgentDTOList = new ArrayList<>();
        if (pageList != null && CollectionUtils.isNotEmpty(pageList.getRecords())) {
            for (SysUserAgent sysUserAgent : pageList.getRecords()) {
                sysUserAgentDTOList.add(toSysUserAgentDTO(sysUserAgent));
            }
        }

        sysUserAgentDTOPage.setTotal(pageList.getTotal());
        sysUserAgentDTOPage.setSize(pageList.getSize());
        sysUserAgentDTOPage.setCurrent(pageList.getCurrent());
        sysUserAgentDTOPage.setRecords(sysUserAgentDTOList);
        return sysUserAgentDTOPage;
    }

    private SysUserAgentDTO toSysUserAgentDTO(SysUserAgent sysUserAgent) {
        if (sysUserAgent == null) {
            return null;
        }
        SysUserAgentDTO sysUserAgentDTO = new SysUserAgentDTO();
        sysUserAgentDTO.setId(sysUserAgent.getId());
        sysUserAgentDTO.setUserName(sysUserAgent.getUserName());
        sysUserAgentDTO.setAgentUserName(sysUserAgent.getAgentUserName());
        sysUserAgentDTO.setStartTime(sysUserAgent.getStartTime());
        sysUserAgentDTO.setEndTime(sysUserAgent.getEndTime());
        sysUserAgentDTO.setStatus(sysUserAgent.getStatus());
        sysUserAgentDTO.setCreateName(sysUserAgent.getCreateName());
        sysUserAgentDTO.setCreateBy(sysUserAgent.getCreateBy());
        sysUserAgentDTO.setCreateTime(sysUserAgent.getCreateTime());
        sysUserAgentDTO.setUpdateName(sysUserAgent.getUpdateName());
        sysUserAgentDTO.setUpdateBy(sysUserAgent.getUpdateBy());
        sysUserAgentDTO.setUpdateTime(sysUserAgent.getUpdateTime());
        sysUserAgentDTO.setSysOrgCode(sysUserAgent.getSysOrgCode());
        sysUserAgentDTO.setSysCompanyCode(sysUserAgent.getSysCompanyCode());
        return sysUserAgentDTO;
    }

    private SysUserAgent toSysUserAgent(SysUserAgentDTO sysUserAgentDTO) {
        if (sysUserAgentDTO == null) {
            return null;
        }
        SysUserAgent sysUserAgent = new SysUserAgent();
        sysUserAgent.setId(sysUserAgentDTO.getId());
        sysUserAgent.setUserName(sysUserAgentDTO.getUserName());
        sysUserAgent.setAgentUserName(sysUserAgentDTO.getAgentUserName());
        sysUserAgent.setStartTime(sysUserAgentDTO.getStartTime());
        sysUserAgent.setEndTime(sysUserAgentDTO.getEndTime());
        sysUserAgent.setStatus(sysUserAgentDTO.getStatus());
        sysUserAgent.setCreateName(sysUserAgentDTO.getCreateName());
        sysUserAgent.setCreateBy(sysUserAgentDTO.getCreateBy());
        sysUserAgent.setCreateTime(sysUserAgentDTO.getCreateTime());
        sysUserAgent.setUpdateName(sysUserAgentDTO.getUpdateName());
        sysUserAgent.setUpdateBy(sysUserAgentDTO.getUpdateBy());
        sysUserAgent.setUpdateTime(sysUserAgentDTO.getUpdateTime());
        sysUserAgent.setSysOrgCode(sysUserAgentDTO.getSysOrgCode());
        sysUserAgent.setSysCompanyCode(sysUserAgentDTO.getSysCompanyCode());
        return sysUserAgent;
    }
}
